package com.tiantian.user.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tiantian.api.RemoteUserSolveService;
import com.tiantian.common.core.constant.UserConstants;
import com.tiantian.common.core.domain.ResponseResult;
import com.tiantian.common.core.domain.page.TableDataInfo;
import com.tiantian.common.core.utils.StringUtils;
import com.tiantian.common.core.validate.EditGroup;
import com.tiantian.common.excel.core.ExcelResult;
import com.tiantian.common.excel.utils.ExcelUtil;
import com.tiantian.common.log.annotation.Log;
import com.tiantian.common.log.enums.BusinessType;
import com.tiantian.common.log.enums.OperatorType;
import com.tiantian.common.satoken.domain.controller.BaseController;
import com.tiantian.user.domain.dto.NewcomerDto;
import com.tiantian.user.domain.entity.SysUser;
import com.tiantian.user.domain.vo.SysUserImportVo;
import com.tiantian.user.listener.SysUserImportListener;
import com.tiantian.user.service.SysRegisterService;
import com.tiantian.user.service.SysUserService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tiantian
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/newcomer")
public class SysNewcomerController extends BaseController {

    private final SysUserService sysUserService;
    private final SysRegisterService registerService;

    @DubboReference
    private RemoteUserSolveService remoteUserSolveService;

    @GetMapping
    @SaCheckPermission("newcomer")
    public ResponseResult<SysUser> selectNewcomerByStudentId(@NotNull(message = "用户ID不能为空") Long userId) {
        SysUser newcomer = sysUserService.selectNewcomerByUserId(userId);
        return ResponseResult.ok(newcomer);
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    @SaCheckPermission("newcomer")
    public TableDataInfo selectByPage(SysUser user) {
        startPage();
        List<SysUser> list = sysUserService.selectNewcomerList(user);
        for (SysUser sysUser : list) {
            // 设置最后一次提交的时间
            String lastReplyTime = remoteUserSolveService.getLastReplyTime(sysUser.getUserId());
            if (StringUtils.isNotEmpty(lastReplyTime)) {
                sysUser.setUpdateTime(LocalDateTime.parse(lastReplyTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
        }
        return getDataTable(list);
    }

    @PutMapping("/update")
    @SaCheckPermission("newcomer")
    @Log(businessType = BusinessType.UPDATE_NEWCOMER, isSaveResponseData = false, operatorType = OperatorType.ADMIN)
    public ResponseResult<Void> updateNewcomer(@Validated(EditGroup.class) @RequestBody NewcomerDto newcomerDTO) {
        newcomerDTO.setUpdateBy(getNickName());
        newcomerDTO.setUpdateTime(LocalDateTime.now());
        return toAjax(sysUserService.updateNewcomer(newcomerDTO));
    }

    /**
     * 一键录取
     */
    @PutMapping("/onekeyEnroll/{userId}")
    @SaCheckPermission("newcomer")
    @Log(businessType = BusinessType.ENROLL, isSaveResponseData = false, operatorType = OperatorType.ADMIN)
    public ResponseResult<Void> onekeyEnroll(@PathVariable Long userId) {
        if (userId == null) {
            return ResponseResult.fail("userId不能为空");
        }
        SysUser sysUser = sysUserService.selectNewcomerByUserId(userId);
        if (ObjectUtil.isEmpty(sysUser)) {
            return ResponseResult.fail("用户不存在, 操作失败");
        }
        NewcomerDto newcomerDTO = new NewcomerDto();
        newcomerDTO.setUserId(userId);
        newcomerDTO.setEnrollStatus(UserConstants.ENROLL_STATUS_ADMITTED);
        newcomerDTO.setUpdateBy(getNickName());
        newcomerDTO.setUpdateTime(LocalDateTime.now());
        return toAjax(sysUserService.updateNewcomer(newcomerDTO));
    }

    /**
     * 获取导入模板
     */
    @GetMapping("/downloadImportTemplate")
    @SaCheckPermission("setting")
    public void downloadImportTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "用户数据", SysUserImportVo.class, response);
    }

    /**
     * 获取导入
     */
    @PostMapping("/import")
    @SaCheckPermission("setting")
    public ResponseResult<ExcelResult<SysUserImportVo>> importCandidate(@RequestPart("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return ResponseResult.fail("导入数据不能为空");
        }
        String extName = FileUtil.extName(file.getOriginalFilename());
        if (!StrUtil.equalsAny(extName, "xlsx", "xls")) {
            return ResponseResult.fail("文件格式不正确,需为excel文件,后缀仅支持xlsx和xls");
        }
        ExcelResult<SysUserImportVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), SysUserImportVo.class, new SysUserImportListener());
        return ResponseResult.ok(excelResult);
    }

}
